// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'xiaogan-gywya',  
  traceUser: true,
})

const db = cloud.database()
var $ = db.command.aggregate
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  console.log(event.name)

  // 获取指定id病人详细信息
  if(event.name == 'get_patient'){
    var result = await db.collection('patient').doc(event.patient_id).get()
    return result.data
  }
  // 获取指定病人的会诊记录单
  else if(event.name == 'get_records'){
    var data = []
    await db.collection('form').aggregate()
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_openid',
      as: 'user_info',
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$basic_info', 0]), '$$ROOT' ])
    })
    .project({
      basic_info: 0
    })
    .match({
      patient_id: event.patient_id,
      form_type: '表单'
    })
    .sort({
      form_time: -1
    })
    .end()
    .then(res => {
      data = res.list
    })
    return data
  }
  // 获取指定病人的医学影像
  else if(event.name == 'get_medicine'){
    var data = []
    await db.collection('form').aggregate()
    .lookup({
      from: 'user',
      localField: '_openid',
      foreignField: '_openid',
      as: 'user_info',
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$basic_info', 0]), '$$ROOT' ])
    })
    .project({
      basic_info: 0
    })
    .match({
      patient_id: event.patient_id,
      form_type: '医学影像'
    })
    .sort({
      form_time: -1
    })
    .skip(event.count)
    .limit(5)
    .end()
    .then(res => {
      data = res.list
    })
    return data
  }
  // 删除指定的会诊记录单或医学影像
  else if(event.name == 'del_records'){
    return await db.collection('form').doc(event.id).remove()
  }
  // 根据指定的id获取病人的会诊记录单或医学影像
  else if(event.name == 'get_record'){
    var result = await db.collection('form').doc(event.id).get()
    return result.data;
  }
  // 根据病人id获取病人所有指标
  else if(event.name == 'get_checks'){
    var result = await db.collection('ao').where({
      patient_id: event.id
    }).get()
    return result.data;
  }
  else{
    // 下面这一小段估计要删掉
    return {
      event,
      openid: wxContext.OPENID,
      appid: wxContext.APPID,
      unionid: wxContext.UNIONID,
    }
  }

}